<?php

namespace App\Console\Commands;

use App\Jobs\LoginRobotJob;
use App\Jobs\LoginSteampoweredRobotJob;
use App\Model\BotsModel;
use App\Model\UserWalletcodeModel;
use App\Service\LogService;
use App\Service\WalletcodeService;
use Illuminate\Console\Command;
use waylaidwanderer\SteamCommunity\Helper;

class SendWalletcode extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'send:walletcode';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'send:walletcode';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送steam钱包充值码';

    /**
     * SendFromOffer constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取当前机器上的机器人Id
     * @return array
     */
    protected function getBotIds()
    {
        return $botIds = BotsModel::where(['client_no' => env('APP_NO')])->pluck('bot_id');
    }

    /**
     * 获取机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    protected function getBotsInfoBybotId($botId)
    {
        return BotsModel::getWalletcodeBotsInfoBybotId($botId);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $connection = (new UserWalletcodeModel())->getConnection();
        $connection->beginTransaction();
        try {
            $botIds = $this->getBotIds();
            $walletcodeRes = UserWalletcodeModel::whereIn('bot_id', $botIds)->where(['walletcode_status' => 0])->orderBy('user_walletcode_id', 'asc')->lockForUpdate()->first();

            if (empty($walletcodeRes)) {
                $connection->rollBack();
                echo "no find need send walletcode " . PHP_EOL;
                exit();
            }

            $userWalletcodeId = $walletcodeRes['user_walletcode_id'];
            $walletcode = $walletcodeRes['walletcode'];
            $botId = $walletcodeRes['bot_id'];
            $bot = $this->getBotsInfoBybotId($botId);
            $steampowered = $bot['steampowered'];

            if (empty($steampowered)) {
                $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
                dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
                $connection->rollBack();
                echo "steam not login botId " . $botId . PHP_EOL;
                exit();
            }

            $botBalanceFront = $steampowered->market()->getWalletBalanceCustom();
            if ($botBalanceFront === 'nologin') {
                $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
                dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
                $connection->rollBack();
                echo "steam not login botId " . $botId . PHP_EOL;
                exit();
            }

            if($botBalanceFront === false){
                echo "not get botBalanceFront userWalletcodeId " . $userWalletcodeId . PHP_EOL;
                exit();
            }

            $data['bot_balance_front'] = $botBalanceFront;

            $sendUrl = WalletcodeService::CONFIRMREDEEMWALLETCODE . '?wallet_code=' . $walletcode;
            $response = $steampowered->cURL($sendUrl, 'https://store.steampowered.com/account/redeemwalletcode');

            $patternValidator = '/<title.*>(.*?)<.*title>/i';
            preg_match($patternValidator, $response, $matchesValidator);
            if (isset($matchesValidator[1]) && in_array(strtolower($matchesValidator[1]), [strtolower('Login'), '登录'])) {
                $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
                dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
                $connection->rollBack();
                echo "steampowered not login botId " . $botId . PHP_EOL;
                exit();
            }

            $response = json_decode($response, true);

            if ($response) {
                if ($response['success'] == 1) {
                    if ($response['detail'] == 0) {
                        echo $response['formattednewwalletbalance'] . PHP_EOL;
                        $data['walletcode_status'] = 1;
                        $data['detail'] = $response['detail'];
                        $data['money'] = Helper::getAmount($response['formattednewwalletbalance']) - $botBalanceFront;
                    } else {
                        echo "send walletcode failed" . PHP_EOL;
                        $data['walletcode_status'] = 2;
                        $data['detail'] = $response['detail'];
                    }
                } else {
                    $data['walletcode_status'] = 2;
                    $data['detail'] = isset($response['detail']) ? $response['detail'] : '';
                    echo "send walletcode bad" . PHP_EOL;
                }
            } else {
                $data['walletcode_status'] = 3;
                echo "send walletcode abnormal" . PHP_EOL;
            }

            $botBalanceAfter = $steampowered->market()->getWalletBalanceCustom();
            if ($botBalanceAfter === 'nologin') {
                echo "not get bot_balance_after" . $botId . PHP_EOL;
                LogService::getInstance()->addActionLog('not get bot_balance_after', 0, 0, 'not get bot_balance_after');
                $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
                dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
            } else {
                $data['bot_balance_after'] = $botBalanceAfter ? $botBalanceAfter : 0;
            }

            UserWalletcodeModel::where(['user_walletcode_id' => $userWalletcodeId])->update($data);

            $connection->commit();
            echo "end send walletcode user_walletcode_id " . $userWalletcodeId . PHP_EOL;
        } catch (\Exception $e) {
            echo $e->getMessage() . PHP_EOL;
            LogService::getInstance()->addActionLog('work_walletcode_error', 0, 0, $e->getMessage());
            $connection->rollBack();
            echo "create walletcode error " . PHP_EOL;
        }
        exit;
    }
}